﻿//Copyright md bravo - feel free to modify this code in any way - just leave this notice ;)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ShareCDN.Engine.Web
{
	public class UploadSlot
	{
		const string TempDataFolderVirtualPath = "~/App_Data/temp/";

		static bool _initialized;

		private static void EnsureDiretory()
		{
			if (!_initialized)
			{
				var tempDirectory = System.Web.Hosting.HostingEnvironment.MapPath(TempDataFolderVirtualPath);
				if (!System.IO.Directory.Exists(tempDirectory))
				{
					System.IO.Directory.CreateDirectory(tempDirectory);
				}
				_initialized = true;
			}

		}


		public UploadSlot()
		{
			EnsureDiretory();
			this._tempFileName = System.Web.Hosting.HostingEnvironment.MapPath(TempDataFolderVirtualPath + Guid.NewGuid().ToString() + ".tmp");
		}


		public enum UploadStatus
		{
			Uploading,
			Converting,
			Uploaded,
			Error

		}

		string _tempFileName;

		public UploadStatus Status { get; private set; }
		public Data.UploadedResult Result { get; private set; }
		public string ContentType { get; set; }
		public DateTime AbsoluteExpiration { get; set; }
		public string FileName { get; set; }
		public bool ForceDownload { get; set; }
		public bool GenerateRemoveLink { get; set; }

		public Exception Error { get; set; }

		public void AppendBytes(byte[] data)
		{
			if (Status != UploadStatus.Uploading)
			{
				throw new Exception("cannot upload - the slot status is" + this.Status.ToString());
			}
			using (var stream = System.IO.File.Open(_tempFileName, System.IO.FileMode.Append))
			{
				stream.Write(data, 0, data.Length);
			}
		}


		public void StartSaving()
		{
			if (Status != UploadStatus.Uploading)
			{
				throw new Exception("cannot start save - the slot status is" + this.Status.ToString());
			}
			this.Status = UploadStatus.Converting;
			System.Threading.ThreadPool.QueueUserWorkItem((x) =>
				{
					var uploadHandle = new Data.UploadHandle();
					try
					{
						using (var stream = System.IO.File.OpenRead(_tempFileName))
						{
							uploadHandle.Stream = stream;
							uploadHandle.ContentType = this.ContentType;
							uploadHandle.AbsoluteExpiration = this.AbsoluteExpiration;
							uploadHandle.FileName = this.FileName;
							uploadHandle.ForceDownload = this.ForceDownload;
							this.Result = Runtime.Manager.Upload(uploadHandle);
							this.Status = UploadStatus.Uploaded;
						}
						System.IO.File.Delete(_tempFileName);
					}
					catch (Exception ex)
					{
						this.Status = UploadStatus.Error;
						this.Error = ex;

					}
					finally
					{
						if (uploadHandle.Stream != null)
						{
							uploadHandle.Stream.Dispose();
						}
					}

				});
		}

		~UploadSlot()
		{
			System.IO.File.Delete(_tempFileName);
		}



	}
}
